package com.a0soft.gphone.aTruffleHog.wnd.stat;
/*
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 3, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * Copyright(C) 2011 
 *   Sam Lu <ysl.sam.lu (at) gmail.com>
 *
 */

import java.text.DecimalFormat;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.a0soft.gphone.aTruffleHog.R;
import com.a0soft.gphone.aTruffleHog.analytic.AnalyticsUtil;
import com.a0soft.gphone.aTruffleHog.di.DeviceInfo;
import com.a0soft.gphone.aTruffleHog.di.DeviceInfoKey;
import com.a0soft.gphone.aTruffleHog.srvc.HttpConnSrvc;
import com.a0soft.gphone.aTruffleHog.util.aDebug;
import com.a0soft.gphone.aTruffleHog.wnd.info.InfoViewCONSTS;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FindDevicesByCameraFrg extends BaseStatFragment {
    private ArrayList<TopDeviceData>   m_data;
    
    private int m_nMinCameraPixels = -1, m_nMaxCameraPixels = -1;
    
    private static final String EXTRA_PREFIX = FindDevicesByCameraFrg.class.getName();
    private static final String EXTRA_MIX = EXTRA_PREFIX + ".min";    
    private static final String EXTRA_MAX = EXTRA_PREFIX + ".max";
    
    private static final String LOG_TAG = FindDevicesByCameraFrg.class.getSimpleName();
    
    ////////////////////////////////////////
    public static FindDevicesByCameraFrg 
    NewInstance() 
    {
        FindDevicesByCameraFrg frg = new FindDevicesByCameraFrg();
        return frg;
    }
    
    public void
    FindDevices(int nMinCameraPixels, int nMaxCameraPixels)
    {
        if (aDebug.ENABLED) aDebug.d(LOG_TAG, "FindDevices(): nMin=" + nMinCameraPixels + ", nMax=" + nMaxCameraPixels);
        m_nMinCameraPixels = nMinCameraPixels;
        m_nMaxCameraPixels = nMaxCameraPixels;
        
        _FindDevices(false);
    }

    @Override public void 
    onCreate(Bundle bdSavedInstanceState)
    {
        super.onCreate(bdSavedInstanceState);
        
        if (aDebug.ENABLED) aDebug.d(LOG_TAG, "onCreate()");
        
        if (bdSavedInstanceState != null) {
            m_nMinCameraPixels = bdSavedInstanceState.getInt(EXTRA_MIX, m_nMinCameraPixels);
            m_nMaxCameraPixels = bdSavedInstanceState.getInt(EXTRA_MAX, m_nMaxCameraPixels);
        }
    }
    
    @Override public void 
    onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putInt(EXTRA_MIX, m_nMinCameraPixels);
        outState.putInt(EXTRA_MAX, m_nMaxCameraPixels);
    }

    @Override public void 
    onActivityCreated(Bundle bdSavedInstanceState)
    {
        super.onActivityCreated(bdSavedInstanceState);
        if (aDebug.ENABLED) aDebug.d(LOG_TAG, "onActivityCreated()");

        AnalyticsUtil.GetInstance(getActivity())
                     .TrackPageView(AnalyticsUtil.PAGE_STAT_FIND_BY_CAMERA);
    }
    
    @Override public View 
    onCreateView(LayoutInflater inflater, ViewGroup vgContainer,
                 Bundle bdSavedInstanceState) 
    {
        View vRoot = super.onCreateView(inflater, vgContainer, bdSavedInstanceState);
        
        if (!getActivity().isFinishing())
            _FindDevices(false);
        
        return vRoot;
    }
    
    private void
    _SetData(JSONObject json)
    {
        try {
            m_lDataTime = json.getLong("t");
            
            JSONArray data = json.getJSONArray("d");
            final int N = data.length();
            if (aDebug.ENABLED)
                aDebug.d(LOG_TAG, "N=" + N);
            
            if (N <= 0) {
                m_data = new ArrayList<TopDeviceData>();
            }
            else {
                m_data = new ArrayList<TopDeviceData>(N);
                for (int i = 0; i < N; i++) {
                    JSONObject obj = data.getJSONObject(i);
                    TopDeviceData td = new TopDeviceData();
                    td.m_fPercentage = (float)obj.getDouble("p");
                    td.m_lCount = obj.getLong("c");
                    td.m_nCameraPixels = obj.getInt("cap");
                    td.m_strManufacture = obj.getString("m");
                    td.m_strModel = obj.getString("d");
                    td.m_strModelID = obj.getString(DeviceInfoKey.K.ST_MID);
                    
                    m_data.add(td);
                }
            }
        }
        catch (JSONException e) {
            if (aDebug.ENABLED)
                aDebug.d(LOG_TAG, "_SetData()", e);
            m_data = new ArrayList<TopDeviceData>();
        }

        _SetDataFinished();
    }
    
    private void
    _SetDataFinished()
    {
        SetStatData(m_data);
        
        m_strMy = null;
        m_nMyIdx = -1;
        
        Context ctx = getActivity();
        if (ctx == null) return;
        
        SetDataFinished();
    }
    
    private void
    _FindDevices(boolean bRedownloadFromServer)
    {
        if (m_nMinCameraPixels < 0 && m_nMaxCameraPixels < 0) {
            if (m_data == null)
                m_data = new ArrayList<TopDeviceData>();
            m_data.clear();
            _SetDataFinished();
            return;
        }
        
        Context ctx = getActivity();
        
        DeviceInfo di = DeviceInfo.GetInstance(ctx);
        final String strDID = di.GetString(DeviceInfoKey.K.UR_ID);
        
        HttpConnSrvc.FindTopDevicesByCamera(ctx, m_nMinCameraPixels, m_nMaxCameraPixels,
                                            strDID, bRedownloadFromServer);
    }

    @Override protected boolean 
    IsMyDownloadCmd(int nCmd)
    {
        return (nCmd == HttpConnSrvc.CMD_FIND_BY_CAMERA);
    }
    
    @Override protected void 
    OnMyDownloadSuccess(int nCmd, JSONObject json)
    {
        super.OnMyDownloadSuccess(nCmd, json);
        
        _SetData(json);
    }
    
    @Override protected void
    SetListItemView(StatData stat, ListItemTagData tag)
    {
        TopDeviceData td = (TopDeviceData)stat;
        
        Context ctx = getActivity();
        
        double dxPixels = td.m_nCameraPixels / (double)InfoViewCONSTS.M_LV;
        String str = new DecimalFormat("#.##").format(dxPixels) + 
                            ctx.getString(R.string.di_ca_m_pixel);
        
        tag.m_tvVersion.setText(str);
        tag.m_tvAPI.setText(td.m_strModel + ", " + td.m_strManufacture);
    }
    
    ////////////////////////////////////
    private static class TopDeviceData extends StatData {
        private String m_strManufacture;
        private String m_strModel;
        @SuppressWarnings("unused") private String m_strModelID;
        private int m_nCameraPixels;
    }
}
